package web.common.core.util;

/**
 * @author Jin Zheng
 * @since 1.0 2021-11-08
 */
public class ByteUtil {
    public static final String STR_EMPTY = "";
    public static final char CH_ZERO = '0';
    public static final int LEN_ZERO = 0;
    public static final int UNIT8_TO_HEX_TIMES = 2;
    public static final int UINT8_MAX = 0xff;

    private ByteUtil() {
    }

    /**
     * 把 byte 数组转换为十六进制字符串
     *
     * @param bytes byte 数组
     * @return 十六进制字符串，范围是00~ff，每个字节占用两个字符
     */
    public static String toHexString(byte[] bytes) {
        if (bytes == null || bytes.length == LEN_ZERO) {
            return STR_EMPTY;
        }
        var sb = new StringBuilder(bytes.length * UNIT8_TO_HEX_TIMES);
        for (byte b : bytes) {
            String hex = Integer.toHexString(b & UINT8_MAX);
            if (hex.length() < UNIT8_TO_HEX_TIMES) {
                sb.append(CH_ZERO);
            }
            sb.append(hex);
        }
        return sb.toString();
    }

}
